import type { Ref } from 'vue';

export interface DragScrollModule {
  tableRef: Ref<HTMLElement | null>;
}

export interface DragState {
  startX: number;
  startY: number;
  scrollTop: number;
  scrollLeft: number;
}

export function useDragScroll(options: DragScrollModule) {
  const { tableRef } = options;

  // 拖动状态
  const dragState: DragState = {
    startX: 0,
    startY: 0,
    scrollTop: 0,
    scrollLeft: 0
  };

  // 处理表头鼠标按下事件
  const handleHeaderMouseDown = (e: MouseEvent) => {
    if (!tableRef.value) return;

    dragState.startX = e.clientX;
    dragState.startY = e.clientY;
    dragState.scrollTop = tableRef.value.scrollTop;
    dragState.scrollLeft = tableRef.value.scrollLeft;

    // 添加全局事件监听器
    document.addEventListener('mousemove', handleMouseMove);
    document.addEventListener('mouseup', handleMouseUp);

    // 防止文本选择
    e.preventDefault();
  };

  // 处理鼠标移动事件
  const handleMouseMove = (e: MouseEvent) => {
    if (!tableRef.value) return;

    const dx = e.clientX - dragState.startX;
    const dy = e.clientY - dragState.startY;

    tableRef.value.scrollTop = dragState.scrollTop - dy;
    tableRef.value.scrollLeft = dragState.scrollLeft - dx;
  };

  // 处理鼠标释放事件
  const handleMouseUp = () => {
    // 移除全局事件监听器
    document.removeEventListener('mousemove', handleMouseMove);
    document.removeEventListener('mouseup', handleMouseUp);
  };

  return {
    handleHeaderMouseDown
  };
}
